package com.service.aliyun.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cdn.model.v20141111.RefreshObjectCachesRequest;
import com.aliyuncs.cdn.model.v20141111.RefreshObjectCachesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.service.aliyun.ICdnService;

/**
 * @author geliyang
 *
 */
@Service
@ConfigurationProperties(prefix="aliyun")
public class CdnServiceImpl implements ICdnService {
	
	static Logger logger = LoggerFactory.getLogger(CdnServiceImpl.class);
	
	private String endpointforcdn;
	
	private String accessKeyId;
	
	private String accessKeySecret;
	
	private IAcsClient client;
	
	private String cdnurl;

	private void init() throws ClientException {
		IClientProfile profile = DefaultProfile.getProfile(endpointforcdn, accessKeyId, accessKeySecret);
		client = new DefaultAcsClient(profile);
	}

	@Override
	public int refreshObjectOfCdn(String objectPath) throws ServerException, ClientException{
		init();
		RefreshObjectCachesRequest refreshObjectCachesRequest = initRequst(objectPath);
		HttpResponse httpResponse = client.doAction(refreshObjectCachesRequest);
		return httpResponse.getStatus();
	}
	
	@Override
	public Map<String,Object> refreshObjectOfCdnForMap(String objectPath) throws ServerException, ClientException{
		init();
		RefreshObjectCachesRequest refreshObjectCachesRequest = initRequst(objectPath);
		RefreshObjectCachesResponse response = client.getAcsResponse(refreshObjectCachesRequest);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("refreshTaskId", response.getRefreshTaskId());
		map.put("requestId", response.getRequestId());
		return map;
	}

	private RefreshObjectCachesRequest initRequst(String objectPath) {
		RefreshObjectCachesRequest refreshObjectCachesRequest = new RefreshObjectCachesRequest();
		refreshObjectCachesRequest.setProtocol(ProtocolType.HTTPS); // 指定访问协议  http | https
		refreshObjectCachesRequest.setAcceptFormat(FormatType.XML); // 指定api返回格式  xml | json
		refreshObjectCachesRequest.setMethod(MethodType.POST); // 指定请求方法  get | post
		// refreshObjectCachesRequest.setObjectType(objectType);//可选， 刷新的类型， 其值可以为File | Directory，默认是File。
		refreshObjectCachesRequest.setObjectPath(cdnurl+"/"+objectPath);
		return refreshObjectCachesRequest;
	}
	
	
}
